package cn.doitedu.flume;

import com.google.gson.Gson;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 涛哥
 * @nick_name "deep as the sea"
 * @contact qq:657270652 wx:doit_edu
 * @site www.doitedu.cn
 * @date 2021-04-13
 * @desc 项目中日志采集用的时间戳拦截器
 */
public class TimestampInterceptor implements Interceptor {
    Gson gson ;
    String headerKey ;

    private TimestampInterceptor(String headerKey){
        this.headerKey = headerKey;
    }


    /**
     * 初始化
     */
    @Override
    public void initialize() {
        gson = new Gson();
    }

    /**
     * 拦截处理逻辑
     * 从日志内容中，抽取到时间戳，放入header
     * @param event
     * @return
     */
    @Override
    public Event intercept(Event event) {

        byte[] body = event.getBody();
        String logData = new String(body);

        LogBean logBean = gson.fromJson(logData, LogBean.class);
        long timeStamp = logBean.getTimeStamp();

        Map<String, String> headers = event.getHeaders();
        if(headers == null) headers = new HashMap<String,String>();
        headers.put(headerKey,timeStamp+"");

        event.setHeaders(headers);

        return event;
    }

    @Override
    public List<Event> intercept(List<Event> list) {
        for (Event event : list) {
            intercept(event);
        }

        return list;
    }


    /**
     * 资源清理
     */
    @Override
    public void close() {
        gson = null;

    }


    public static class MyBuilder implements Interceptor.Builder{

        String headerKey = "timestamp";
        /**
         * 构造拦截器对象的方法
         * @return
         */
        @Override
        public Interceptor build() {

            return new TimestampInterceptor(headerKey);
        }

        /**
         * 获取配置参数的方法
         * @param context
         */
        @Override
        public void configure(Context context) {
            headerKey = context.getString("headerKey");
        }
    }

}
